# Copyright (c) 2021 Presto Labs Pte. Ltd.
# Author: gekim

from absl import app, flags
import json
import requests
import sys
from collections import OrderedDict
from xunkemgmt_client.tool.slack_noti import send_to_slack

FLAGS = flags.FLAGS


def load_from_file():
  with open(FLAGS.coinone_unit_map_file) as f:
    unit_map_json = json.load(f)
    return unit_map_json["feed"]["exchanges"]["Spot.Coinone.v2"]["unit_map"]


def load_from_web():
  coinone_tradepair_url = 'https://api.coinone.co.kr/public/v2/markets/KRW'
  unitmap_data = OrderedDict()
  resp = requests.get(coinone_tradepair_url)
  if resp and resp.status_code == requests.codes.ok:
    data = resp.json()
    for market in data['markets']:
      pair_str = market["target_currency"] + '-' + market["quote_currency"]
      unitmap_data[pair_str] = market['price_unit']
  return unitmap_data


def save_to_file(unit_maps_from_file):
  with open(FLAGS.coinone_unit_map_file, 'w') as f:
    data_out = {"feed": {"exchanges": {"Spot.Coinone.v2": {}}}}
    data_out["feed"]["exchanges"]["Spot.Coinone.v2"]["unit_map"] = unit_maps_from_file
    json.dump(data_out, f, indent=2, sort_keys=True)


def main(_):
  unit_maps_from_file = load_from_file()
  unit_maps_from_web = load_from_web()
  out_str = ""
  for k, v in unit_maps_from_file.items():
    if k in unit_maps_from_web and unit_maps_from_web[k] != v:
      out_str += "[Coinone] The price unit of \'%s\' has been changed from %s to %s \n" \
                % (k, v, unit_maps_from_web[k])
      unit_maps_from_file[k] = unit_maps_from_web[k]
  if len(out_str) > 0:
    save_to_file(unit_maps_from_file)
    if FLAGS.slack_receiver is not None:
      send_to_slack(out_str, FLAGS.slack_receiver, 'msg')
    sys.stdout.write('updated')
    return
  sys.stdout.write('noupdate')


if __name__ == "__main__":
  flags.DEFINE_string('coinone_unit_map_file', 'data/coin2/feed/coinone_unit_map.json',
                      'Unit Map config file of coinone.')
  flags.DEFINE_string('slack_receiver', None, 'slack channel')
  app.run(main)
